# -*- coding: utf-8 -*-

#   This file is part of emesene.
#
#    Emesene is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    emesene is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with emesene; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

VERSION = '0.1'

import Plugin
import urllib2

ERROR = ''

ARTICLE_START='/td>\n</tr>\n</table>\n<p>'

ARTICLE_END = '<table id="toc" class="toc" summary="Tabla de contenidos">'

NOT_FOUND='<div class="noarticletext">'

WIKI_URL = 'http://%s.wikipedia.org/wiki/%s'

AMBIG = '<div class="messagebox cleanup" id="disambig" style="clear: both;">'

class Wiki(object):
    def __init__(self,lang):
        self.lang = lang

    def request(self,url):
        req= urllib2.Request(url)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1) Gecko/20061010 Firefox/2.0')
        req.add_header('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7')
        req.add_header('Accept', 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5')
        req.add_header('Accept-Language', 'es-ar,es;q=0.5')
        o=urllib2.urlopen(req)
        return o.read()

    def stripTags(self,s):
        intag = [False]
    
        def chk(c):
            if intag[0]:
                intag[0] = (c != '>')
                return False
            elif c == '<':
                intag[0] = True
                return False
            return True
    
        return ''.join(c for c in s if chk(c))

    def getArticle(self, wikiword):
        url = self.getUrl(wikiword)
        data = self.request(url)
        if data.count(NOT_FOUND):
            return 'Not found that article'
        elif data.count(AMBIG):
            return 'Ambiguo'
        else:
            try:
                data = data.split(ARTICLE_START)[1].split(ARTICLE_END)[0]
                return self.stripTags( data )
            except Exception, e:
                print e
                return 'Somthing goes wrong..'
    def getUrl(self,wikiword):
        return WIKI_URL%(self.lang,urllib2.quote(wikiword))


class MainClass( Plugin.Plugin ):
    '''Main plugin class'''
    
    description = _( 'Wikipedia' )
    authors = { 'Roger Duran' : 'RogerDuran at gmail dot com' }
    website = 'http://www.rogerpc.com.ar'
    displayName = _( 'Wikipedia' )
    name = 'Wikipedia'
    def __init__( self, controller, msn ):
        '''Contructor'''
        
        Plugin.Plugin.__init__( self, controller, msn )
        
        self.description = _( 'Wikipedia' )
        self.authors = { 'Roger Duran' : 'RogerDuran at gmail dot com' }
        self.website = 'http://www.rogerpc.com.ar'
        self.displayName = _( 'Wikipedia' )
        self.name = 'Wikipedia'

        self.config = controller.config
        self.config.readPluginConfig(self.name)

        self.lang = self.config.getPluginValue( self.name, 'lang', 'en' )
        self.wiki = Wiki(self.lang)
        self.Slash = controller.Slash
        
        self.controller = controller

    def start( self ):
        '''start the plugin'''
        self.Slash.register('wiki', self.slashCommand, 'Wikipedia article parser')
        self.enabled = True
        
    def stop( self ):    
        '''stop the plugin'''
        self.Slash.unregister('wiki')
        self.enabled = False
        
    def slashCommand( self, slashAction ):
        wikiword = str(slashAction.getParams())
        data = self.wiki.getArticle(wikiword)
        if len(data) > 500:
            data=data[:500]+'... '+_('Read more in ')+self.wiki.getUrl(wikiword)
        slashAction.outputText(data)

        
    def action( self ):
        pass
    
    def check( self ):
        '''
        check if everything is OK to start the plugin
        return a tuple whith a boolean and a message
        if OK -> ( True , 'some message' )
        else -> ( False , 'error message' )
        '''
        if ERROR != '':
            return ( False, ERROR )
            
        return ( True, 'Ok' )
        
    def configure( self ):
        l=[]
        l.append( Plugin.Option( 'lang', str, _('Language:'), '', self.config.getPluginValue( self.name, 'lang', self.lang )) )
        
        response = Plugin.ConfigWindow( _( 'Wikipedia plugin config' ), l ).run()
        if response != None:
            self.lang = response['lang'].value
            self.wiki.lang = self.lang

            self.config.setPluginValue( self.name,'lang', self.lang )
        return True
